package com.ithuameng.notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ithuameng.notice.model.MessageLog;
import com.ithuameng.notice.model.Notice;
import com.ithuameng.notice.service.IMessageLogService;
import com.ithuameng.notice.service.INoticeService;
import com.ithuameng.notice.util.R;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 消息通知控制器
 */
@RestController
@RequestMapping(value = "/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IMessageLogService messageLogService;

    /**
     * 模拟会员消息自动发送--用户提交订单/退款等操作
     */
    @GetMapping("/send")
    public void sendMessage(String message) {
        // 创建消息对象 1为超级管理员ID(此案例不需要也可以)  100001L模拟当前登录会员
        Notice notice = new Notice(1, 100001L, message, false, LocalDateTime.now());
        // 新消息缓存到redis中
        redisTemplate.opsForList().leftPush("msgs", notice);
        redisTemplate.expire("msgs", 365, TimeUnit.DAYS);
        // 生成消息唯一ID
        String msgId = UUID.randomUUID().toString();
        MessageLog messageLog = new MessageLog();
        messageLog.setMsgId(msgId);
        messageLog.setTryTime(LocalDateTime.now().plusMinutes(1));
        messageLog.setCreateTime(LocalDateTime.now());
        messageLogService.save(messageLog);
        // 发送mq消息
        rabbitTemplate.convertAndSend("system_notice_exchange", null, message, new CorrelationData(msgId));
    }

    /**
     * 获取未读的消息数量(DB中获取)
     */
    @GetMapping("/unread")
    public R<Integer> getUnreadQuantity() {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Notice.STATE, false);
        return new R<>(noticeService.count(queryWrapper));
    }

    /**
     * 将redis中的新消息保存到DB中
     */
    @GetMapping("/cache")
    public void handleCacheUnread() {
        List<Notice> ns = redisTemplate.opsForList().range("msgs", 0, -1);
        if (ns != null && ns.size() > 0) {
            noticeService.saveBatch(ns);
            redisTemplate.delete("msgs");
        }
    }
}
